package com.licode.codekit.buildprj;

import com.intellij.ui.Gray;
import com.intellij.ui.components.JBScrollPane;
import com.licode.codekit.db.AssembledDb;
import com.licode.codekit.db.Table;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.util.ArrayList;

/**
 * @author licode
 */
public class TableUiBuilder {
    private JCheckBoxList tableList;
    private final DefaultListModel<JCheckBox> model = new DefaultListModel<>();
    private final SpinnerNumberModel spModel = new SpinnerNumberModel();
    private final JSpinner tablePrefixContent = new JSpinner(spModel);
    private final JLabel tablePrefixName = new JLabel("表前缀：", 4);

    public TableUiBuilder() {
    }

    public JComponent initTablesView() {
        tableList = new JCheckBoxList(model);
        tableList.setAutoscrolls(true);
        tableList.setBorder(new LineBorder(Gray._80, 1));
        JBScrollPane sPane = new JBScrollPane(tableList);

        sPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        sPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        sPane.setOpaque(false);
        sPane.getViewport().setOpaque(false);

        sPane.setSize(420, 180);
        sPane.getViewport().setSize(420, 180);
        sPane.setBounds(0, 0, 420, 180);

        return sPane;
    }

    public void refreshTables(AssembledDb assembledDb) {
        model.clear();
        if (!assembledDb.getTables().isEmpty()) {
            for (Table item: assembledDb.getTables()) {
                model.addElement(new JCheckBox(item.getName()));
            }
        }

        if (null != tableList) {
            tableList.updateUI();
        }
    }

    public java.util.List<Table> getSelectedTable(AssembledDb assembledDb) {
        java.util.List<Table> tabs = new ArrayList<>();

        if (null != tableList) {
            ListModel<JCheckBox> listModel = tableList.getModel();
            if (null != listModel) {
                for (int i = 0; i < listModel.getSize(); ++i) {
                    JCheckBox jcb = listModel.getElementAt(i);
                    if (jcb.isSelected()) {
                        tabs.add(assembledDb.getTables().get(i));
                    }
                }
            }
        }

        return tabs;
    }
}
